package com.xie.smfs.item;

import com.xie.smfs.entity.GhostEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.world.World;

public class CoffinNailItem extends Item {
    public CoffinNailItem(Settings settings) {
        super(settings);
    }

    @Override
    public ActionResult useOnEntity(ItemStack stack, PlayerEntity user, LivingEntity entity, Hand hand) {
        if (entity instanceof GhostEntity) {
            GhostEntity ghost = (GhostEntity) entity;
            World world = user.getWorld();
            // 确保所有逻辑在服务端执行
            if (!world.isClient) {
                if (!ghost.isSuppressed()) {
                    applySuppression(ghost, user, stack);
                    // 播放不死图腾爆炸音效
                    world.playSound(null, ghost.getX(), ghost.getY(), ghost.getZ(), SoundEvents.ITEM_TOTEM_USE, SoundCategory.NEUTRAL, 1.0F, 1.0F);
                    return ActionResult.SUCCESS;
                }
            }
            return ActionResult.SUCCESS;
        }
        return ActionResult.PASS;
    }

    @Override
    public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
        return TypedActionResult.pass(user.getStackInHand(hand));
    }

    // 检查目标是否为可被压制的鬼
    private boolean canSuppressGhost(GhostEntity ghost) {
        return ghost != null && !ghost.isSuppressed();
    }

    // 对鬼应用压制效果
    private void applySuppression(GhostEntity ghost, PlayerEntity player, ItemStack stack) {
        if (ghost.isDeadlocked() || ghost.hasCoffinNail()) {
            return;
        }
        ghost.setDeadlocked(true);
        ghost.setSuppressed(true);
        ghost.disableGhostDomain();
        ghost.disableKillingRules();
        ItemStack nailCopy = stack.copy();
        stack.decrement(1);
        ghost.setCoffinNail(nailCopy);
    }
}